<template>
  <div class="article-list" :style="{ height: sreenHeight }">
    <van-pull-refresh
      v-model="isreFreshLoading"
      @refresh="onRefresh"
      :success-text="successText"
      success-duration="1200"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <ArticleItem
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  data() {
    return {
      list: [], // 列表数据
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      timestamp: null, // 请求获取下一页数据的时间戳
      error: false, // 控制失败的提示状态
      isreFreshLoading: false, // 下拉刷新加载中
      successText: '刷新成功',
      sreenHeight: ''
    }
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },

  methods: {
    // 加载列表
    async onLoad() {
      try {
        // 获取数据
        const { data: res } = await this.$api.getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || +new Date() // 根据时间戳获取分页数据
        })
        // if (Math.random() > 0.5) throw new Error() // 测试代码 捕获异常
        const { results } = res.data
        this.list.push(...results) // 追加数据到 list
        this.loading = false
        if (res.data.pre_timestamp) {
          // 获取下一页的时间戳
          this.timestamp = res.data.pre_timestamp
        } else {
          // 所有数据展示完成 finished 为 true
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    // 下拉刷新
    async onRefresh() {
      try {
        const { data: res } = await this.$api.getArticles({
          channel_id: this.channel.id,
          timestamp: +new Date() // 下拉刷新获取最新数据,参数为当前时间戳
        })
        // if (Math.random() >= 0.5) throw new Error() // 测试代码 错误捕获
        this.list.unshift(...res.data.results)
        this.successText = `刷新成功,更新了${res.data.results.length}条数据`
        this.isreFreshLoading = false
      } catch (err) {
        // 请求出错
        this.isreFreshLoading = false
        this.successText = '刷新失败,请稍后重试'
      }
    }
  },
  mounted() {
    this.sreenHeight =
      window.screen.availHeight -
      document.querySelector('.layout-tabbar').offsetHeight -
      document.querySelector('.van-nav-bar__content').offsetHeight -
      document.querySelector('.van-tabs__wrap').offsetHeight +
      'px'
  }
}
</script>

<style lang="less" scoped>
.article-list {
  overflow-y: auto;
}
</style>
